import { defineStore } from 'pinia'
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import api from '@/api/user'

export const useUserStore = defineStore('user', () => {
    const router = useRouter()
    
    // 状态
    const token = ref(localStorage.getItem('token') || '')
    const userInfo = ref(JSON.parse(localStorage.getItem('userInfo')) || null)
    
    // 登录
    const login = async (form) => {
        try {
            const res = await api.login(form)
            token.value = res.token
            userInfo.value = res.user
            localStorage.setItem('token', token.value)
            localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
            await router.push('/')
            return true
        } catch (error) {
            reset()
            return false
        }
    }
    
    // 注册
    const register = async (form) => {
        try {
            await api.register(form)
            return true
        } catch (error) {
            return false
        }
    }
    
    // 退出登录
    const logout = async () => {
        try {
            await api.logout()
            reset()
            await router.push('/login')
            return true
        } catch (error) {
            return false
        }
    }
    
    // 检查登录状态
    const checkLogin = async () => {
        try {
            const res = await api.checkLogin()
            if (res && res.user) {
                token.value = localStorage.getItem('token')
                userInfo.value = res.user
                localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
                return true
            }
        } catch (error) {
            reset()
        }
        return false
    }
    
    // 重置状态
    const reset = () => {
        token.value = ''
        userInfo.value = null
        localStorage.removeItem('token')
        localStorage.removeItem('userInfo')
    }
    
    return {
        token,
        userInfo,
        login,
        register,
        logout,
        checkLogin,
        reset
    }
})